package com.app.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.app.common.EducationTool;
import com.app.common.ExperienceTool;
import com.app.common.IndustryTool;
import com.app.common.SystemConstant;
import com.app.conf.RedisService;
import com.app.mapper.UserMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.util.*;
import com.app.vo.ExperienceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RestController
public class ComRecruitersController {

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    ComRecruitersService comRecruitersService;
    @Autowired
    EnterpriseService enterpriseService;
    @Autowired
    UserService userService;
    @Autowired
    JobPublishService jobPublishService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    IndustryService industryService;

    @Autowired
    private RedisService redisService;

    //企业注册第一步
    @PostMapping("/addComOne")
    public Result<Object> addCom(@RequestParam(required = false) String faceUrl,
                                 @RequestParam("realName") String realName,
                                 @RequestParam("comId") String comId,
                                 @RequestParam("comPosition") String comPosition,
                                 @RequestParam("numId") String numId,
                                 @RequestParam("type") String type,
                                 @RequestParam("streetId") Integer streetId,
                                 HttpServletRequest request) {
        String token = request.getHeader("token");
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }

        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }

        ComRecruitersModel com = new ComRecruitersModel();
        com.setRealName(realName);

        com.setComPosition(comPosition);
        com.setUpTime(String.valueOf(CommonHelp.getNowTimestamp()));
        EnterpriseModel enterpriseModel = new EnterpriseModel();
        if(StringTool.isEmpty(comId))
        {
           String result = TyUtil.executeGet(TyUtil.url+numId,TyUtil.token);
            JSONObject resultJson = JSONObject.parseObject(result);
           if(!resultJson.get("error_code").equals(0))
           {
               return Result.success(0);
           }else{
               String msg = resultJson.get("result").toString();
               JSONObject msgJson = JSONObject.parseObject(msg);
               enterpriseModel.setRegno((String) msgJson.get("regNumber"));
               String regCapital = (String) msgJson.get("regCapital");
               String industry = (String) msgJson.get("industry");
               IndustryModel industryModel = industryService.getModelByName(industry);
               String str1 = "";
               if(StringTool.isNotEmpty(regCapital))
               {
                   if(regCapital.contains("万")) {
                       str1 = regCapital.substring(0, regCapital.indexOf("万"));
                   }else {
                       str1 = regCapital.substring(0, regCapital.indexOf("人"));
                       Double one = Double.valueOf(str1);
                       Double two = 10000.0;
                        Double news = one/two;
                       DecimalFormat decimalFormat = new DecimalFormat("###0.0000");
                       str1 = decimalFormat.format(news);
                   }
               }
               enterpriseModel.setRegcap(str1);
               if(industryModel!=null)
               {
                   enterpriseModel.setEnterpriseType(String.valueOf(industryModel.getIndustryCode()));
               }
               enterpriseModel.setEnterpriseName(msgJson.get("name").toString());
               enterpriseModel.setRegorgCn(msgJson.get("regInstitute").toString());
               enterpriseModel.setEnterpriseAddress(msgJson.get("regLocation").toString());
               enterpriseModel.setBusinessScope(msgJson.get("businessScope").toString());
               enterpriseModel.setBrandName(msgJson.get("alias").toString());
               String estdate = conversionTime(msgJson.get("estiblishTime").toString());
               enterpriseModel.setEstdate(estdate);
               enterpriseModel.setLegalPersonName(msgJson.get("legalPersonName").toString());
               enterpriseModel.setErterpriseIdNum(msgJson.get("creditCode").toString());
               enterpriseModel.setCrtTime(String.valueOf(CommonHelp.getNowTimestamp()));
               enterpriseModel.setStreetId(streetId);
               enterpriseService.insert(enterpriseModel);
               comId = enterpriseModel.getId().toString();
           }
        }else{
            enterpriseModel = enterpriseService.findModelById(Integer.valueOf(comId));
            enterpriseModel.setStreetId(streetId);
            enterpriseService.update(enterpriseModel);
        }
        com.setComId(Integer.parseInt(comId));
        if(StringTool.isEmpty(faceUrl))
        {
            faceUrl = SystemConstant.DEFAULT_FACE_URL;
        }
        if ("add".equals(type)) {
            comRecruitersService.insert(com);
            user.setRRegisterState(1);
            user.setFaceUrl(faceUrl);
            user.setRId(com.getId());
            userService.update(user);
        } else {
            com.setId(user.getRId());
            user.setFaceUrl(faceUrl);
            userService.update(user);
            comRecruitersService.update(com);
            com = comRecruitersService.getComRecruitersById(user.getRId());
            user.setCom(com);
        }
        UserModel userModel = new UserModel();
        userModel.setRealName(user.getRealName());
        userModel.setFaceUrl(user.getFaceUrl());
        userModel.setMobile(user.getMobile());
        userModel.setAuthenticationStatus(1);
        return Result.success(null);
    }


    //传入时间戳即可
    public String conversionTime(String timeStamp) {
        //yyyy-MM-dd HH:mm:ss 转换的时间格式  可以自定义
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //转换
        String time = sdf.format(new Date(Long.parseLong(timeStamp)));
        return time;
    }

    @PostMapping("/addComTwo")
    public Result<Object> addComThree(@RequestParam("upLicense") String upLicense,
                                      @RequestParam("upRecruit") String upRecruit,
                                      @RequestParam("idCardJust") String idCardJust,
                                      @RequestParam("idCardBack") String idCardBack,
                                      HttpServletRequest request) {
        String token = request.getHeader("token");
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }

        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        ComRecruitersModel com = comRecruitersService.getComRecruitersById(user.getRId());
        //修改HR状态
        com.setUpTime(String.valueOf(CommonHelp.getNowTimestamp()));
        com.setUpRecruit(upRecruit);
        com.setUpLicense(upLicense);
        com.setIdCardJust(idCardJust);
        com.setIdCardBack(idCardBack);
        comRecruitersService.update(com);
        user.setRRegisterState(3);
        userService.update(user);
        user.setCom(com);
        UserModel userModel = new UserModel();
        userModel.setRealName(user.getRealName());
        userModel.setFaceUrl(user.getFaceUrl());
        userModel.setMobile(user.getMobile());
        userModel.setAuthenticationStatus(3);
        return Result.success(userModel);
    }

    @GetMapping("/toRealNameExamine")
    public Result<Object> toRealNameExamine(
            HttpServletRequest request, String userKey, Integer type) {

        String token = null;
        if (type == 2) {
            if (!redisService.existKey(userKey)) {
                return Result.error(500, "验证已过期请重新扫码");
            }
            JSONObject json = (JSONObject) redisService.getStringKey(userKey);

            if (json != null) {
                token = json.getString("token");
            }
        }
        if (type == 1) {
            token = request.getHeader("token");
        }

        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }

        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }

        FileSystemUtils.deleteRecursively(new File(SystemConstant.DEFAULT_PDF_URL+"/qrcode/"+userKey+".png"));
        user.setRRegisterState(2);
        userService.update(user);
        return Result.success(null);
    }

    @PostMapping("/addComThree")
    public Result<Object> addComTwo(@RequestParam("logoUrl") String logoUrl,
                                    @RequestParam("brandName") String brandName,
                                    @RequestParam("comType") String comType,
                                    @RequestParam("scaleId") int scaleId,
                                    @RequestParam("welfare") String welfare,
                                    @RequestParam("comIntroduction") String comIntroduction,
                                    @RequestParam("type") String type,
                                    HttpServletRequest request) {
        String token = request.getHeader("token");
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }

        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        ComRecruitersModel com = comRecruitersService.getComRecruitersById(user.getRId());
        //修改企业信息
        EnterpriseModel model = new EnterpriseModel();
        model.setId(com.getComId());
        model.setLogoUrl(logoUrl);
        model.setBrandName(brandName);
        model.setEnterpriseType(comType);
        model.setScaleId(scaleId);
        model.setWelfare(welfare);
        model.setEnterpriseIntroduction(comIntroduction);
        enterpriseService.update(model);
        //修改HR状态
        ComRecruitersModel cr = new ComRecruitersModel();
        if (type.equals("add")) {
            user.setRRegisterState(4);
            userService.update(user);
        }
        cr.setId(com.getId());
        cr.setComId(com.getComId());
        comRecruitersService.update(cr);
        return Result.success(null);
    }


    @GetMapping("/getToExamine")
    public Result<Object> getToExamine(HttpServletRequest request) {
        String token = request.getHeader("token");
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }

        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        return Result.success(user.getRRegisterState());
    }

    @GetMapping("/getComRecruiters")
    public Result<Object> getComRecruiters(
            HttpServletRequest request) {
        String token = request.getHeader("token");
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }

        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        if(user.getRId()!=null)
        {
            ComRecruitersModel com = comRecruitersService.getComRecruitersById(user.getRId());
            EnterpriseModel enterpriseModel = enterpriseService.findModelById(com.getComId());
            com.setComName(enterpriseModel.getEnterpriseName());
            com.setComShortName(enterpriseModel.getBrandName());
            com.setErterpriseIdNum(enterpriseModel.getErterpriseIdNum());
            user.setCom(com);
        }
        return Result.success(user);
    }

    @GetMapping("/getComRecruitersById")
    public Result<Object> getComRecruitersById(
            HttpServletRequest request) {
        String token = request.getHeader("token");
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }

        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        ComRecruitersModel com = new ComRecruitersModel();
        if(user.getRId()!=null)
        {
            com = comRecruitersService.getComRecruitersById(user.getRId());
        }
        return Result.success(com);
    }

    //查询招聘者信息
    @GetMapping("/getComRecruitersDetail")
    public Result<Object> getComRecruitersDetail(Integer id,
                                                 HttpServletRequest request) {
        String token = request.getHeader("token");
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        int page = Integer.valueOf(request.getParameter("page"));
        int limit = Integer.valueOf(request.getParameter("limit"));
        ComRecruitersModel com = comRecruitersService.getComRecruitersById(id);
        Map<String, Object> map3 = new HashMap<>();
        map3.put("r_id", com.getId());
        UserModel userModel = userMapper.selectByMap(map3).get(0);
        com.setComImg(userModel.getFaceUrl());
        EnterpriseModel enterpriseModel = enterpriseService.findLogoById(com.getComId());
        com.setEnterpriseName(enterpriseModel.getEnterpriseName());
        JobPublishModel jobPublish = new JobPublishModel();
        jobPublish.setEnrollId(com.getComId());
        jobPublish.setRecruitState(3);
        jobPublish.setRecruitType(1);
        jobPublish.setPage((page - 1) * limit);
        jobPublish.setLimit(limit);
        int count = jobPublishService.getJobPublishCountByHrId(id);
        com.setCount(count);
        List<JobPublishModel> modelList = jobPublishService.getJobPublishListByModel(jobPublish);
        if (modelList != null && modelList.size() > 0) {
            for (int i = 0; i < modelList.size(); i++) {
                int expId = modelList.get(i).getExpId();
                int eduId = modelList.get(i).getEduId();
                for (int j = 0; j < ExperienceTool.EXPERIENCE_VO_LIST.size(); j++) {
                    if (expId == ExperienceTool.EXPERIENCE_VO_LIST.get(j).getId()) {
                        if (expId == 1 || expId == 6) {
                            modelList.get(i).setExpRequireText(ExperienceTool.EXPERIENCE_VO_LIST.get(j).getData());
                        } else {
                            modelList.get(i).setExpRequireText(ExperienceTool.EXPERIENCE_VO_LIST.get(j).getData() + "年");
                        }

                    }
                }
                for (int j = 0; j < EducationTool.EDUCATION_VO_LIST.size(); j++) {
                    if (eduId == EducationTool.EDUCATION_VO_LIST.get(j).getId()) {
                        modelList.get(i).setMinEducationText(EducationTool.EDUCATION_VO_LIST.get(j).getData());
                    }
                }
            }
        }
        com.setJobPublishModelList(modelList);

        return Result.success(com);
    }

    //    改
    @PostMapping("/updateCom")
    public Result<Object> updateCom(@RequestParam("id") int id,
                                    @RequestParam("card") String card,
                                    @RequestParam("logo_url") String logo_url,
                                    @RequestParam("brand_name") String brand_name,
                                    @RequestParam("com_fullname") String com_fullname,
                                    @RequestParam("industry") String industry,
                                    @RequestParam("financing") String financing,
                                    @RequestParam("min_num") String min_num,
                                    @RequestParam("max_num") String max_num,
                                    @RequestParam("start_time") String start_time,
                                    @RequestParam("end_time") String end_time,
                                    @RequestParam("com_profile") String com_profile,
                                    @RequestParam("comState") int comState
    ) {
        String sql = "update tb_com_enroll set card= '" + card + "',logo_url='" + logo_url + "',brand_name='" + brand_name + "',com_fullname='" + com_fullname + "',industry='" + industry + "',financing='" + financing + "',min_num='" + min_num + "',max_num='" + max_num + "',start_time='" + start_time + "',end_time='" + end_time + "',com_profile='" + com_profile + "'where  id='" + id + "' and comState='" + comState + "'  ";

        jdbcTemplate.update(sql);

        return Result.success(null);
    }

    @GetMapping("/industry")
    public Result<Object> industry() {
        List<ExperienceVo> industryList = new ArrayList<>();
        for (int i = 1; i <= IndustryTool.myMap.size(); i++) {
            ExperienceVo vo = new ExperienceVo();
            vo.setId(i);
            vo.setData(IndustryTool.myMap.get(i));
            industryList.add(vo);
        }
        return Result.success(industryList);
    }



}